<template>
  <div class="business-menus-page">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.permissionName" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增菜单</el-button>
          <el-button @click="handleSyncMenu">同步菜单</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          row-key="permissionId"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          default-expand-all
          class="menus-table"
        >
          <el-table-column prop="permissionName" label="权限名称" />
          <el-table-column prop="permissionUri" label="URI" :show-overflow-tooltip="true" />
          <el-table-column prop="permission" label="组件" :show-overflow-tooltip="true" />
          <el-table-column prop="icon" label="图标" />
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column prop="resourceType" label="权限类型" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.resourceType === 'menu'">菜单</el-tag>
              <el-tag v-else-if="scope.row.resourceType === 'button'" type="success">按钮</el-tag>
              <el-tag v-else-if="scope.row.resourceType === 'catalog'" type="warning">目录</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="scope">
              <div class="table-actions">
                <button-table type="edit" @click="handleEdit(scope.row)" size="small" />
                <button-table type="add" @click="handleAddChild(scope.row)" size="small" />
                <el-popconfirm title="确定删除该菜单吗？" @confirm="handleDelete(scope.row)">
                  <template #reference>
                    <button-table type="delete" @click.stop="() => {}" size="small" />
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 新增/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="menuFormRef" :model="menuForm" :rules="menuRules" label-width="100px">
        <el-form-item label="上级菜单" prop="permissionPid">
          <el-tree-select
            v-model="menuForm.permissionPid"
            :data="menuTreeData"
            node-key="permissionId"
            :props="{ label: 'permissionName', children: 'children' }"
            value-key="permissionId"
            placeholder="请选择上级菜单"
            check-strictly
            filterable
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="menuForm.permissionName" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入菜单路径" />
        </el-form-item>
        <el-form-item label="URI" prop="permissionUri">
          <el-input v-model="menuForm.permissionUri" placeholder="请输入URI" />
        </el-form-item>
        <el-form-item label="权限类型" prop="resourceType">
          <el-select
            v-model="menuForm.resourceType"
            placeholder="请选择权限类型"
            style="width: 100%"
          >
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="目录" value="catalog" />
          </el-select>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <IconSelector :default-icon="menuForm.icon" @get-icon="handleIconChoose" width="100%" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="menuForm.sort"
            :min="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input
            v-model="menuForm.describe"
            type="textarea"
            placeholder="请输入描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitMenu">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 同步菜单对话框 -->
    <el-dialog
      v-model="syncDialogVisible"
      title="同步菜单"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="syncFormRef" :model="syncForm" :rules="syncRules" label-width="100px">
        <el-form-item label="同步范围" prop="syncAll">
          <el-radio-group v-model="syncForm.syncAll">
            <el-radio :label="true">同步所有</el-radio>
            <el-radio :label="false">同步指定商家</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除菜单">
          <el-checkbox v-model="syncForm.delMenu" />
        </el-form-item>
        <el-form-item v-if="!syncForm.syncAll" label="商家账号" prop="syncBusinessUsername">
          <el-input v-model="syncForm.syncBusinessUsername" placeholder="请输入商家账号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="syncDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="syncLoading" @click="submitSync">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图标选择组件 -->
    <IconSelector ref="iconsRef" @get-icon="handleIconChoose" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, computed } from 'vue'
  import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
  import { BusinessMenuService } from '@/api/setupApi'
  import { BusinessPermissionType, BusinessPermissionTreeType } from '@/api/model/setupModel'
  import IconSelector from '@/components/Icons/IconSelector.vue'

  // 表单引用
  const menuFormRef = ref<FormInstance>()
  const syncFormRef = ref<FormInstance>()
  const searchFormRef = ref<FormInstance>()

  // 数据状态
  const loading = ref(false)
  const submitLoading = ref(false)
  const syncLoading = ref(false)
  const dialogVisible = ref(false)
  const syncDialogVisible = ref(false)

  // 搜索表单
  const searchForm = reactive({
    permissionName: '',
    page: 1,
    pageSize: 10
  })

  // 菜单表单
  const menuForm = reactive<BusinessPermissionType>({
    permissionId: undefined,
    permissionPid: undefined,
    permissionName: '',
    permissionUri: '',
    permission: '',
    icon: '',
    describe: '',
    resourceType: 'menu',
    sort: 0
  })

  // 同步表单
  const syncForm = reactive({
    syncAll: true,
    syncBusinessUsername: '',
    delMenu: false
  })

  // 表单验证规则
  const menuRules = {
    permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
    permission: [{ required: true, message: '请输入菜单路径', trigger: 'blur' }],
    resourceType: [{ required: true, message: '请选择权限类型', trigger: 'change' }]
  }

  const syncRules = {
    syncBusinessUsername: [{ required: true, message: '请输入商家账号', trigger: 'blur' }]
  }

  // 表格数据
  const tableData = ref<BusinessPermissionTreeType[]>([])
  const menuTreeData = ref<BusinessPermissionTreeType[]>([])
  const total = ref(0)

  // 对话框标题
  const dialogTitle = computed(() => {
    return menuForm.permissionId ? '编辑菜单' : '新增菜单'
  })

  // 操作状态
  const isEdit = ref(false)

  // 获取最大排序值
  const getMaxSort = async () => {
    try {
      const res = await BusinessMenuService.getMaxSort()
      menuForm.sort = res.data || 0
    } catch (error) {
      console.error('获取最大排序值失败:', error)
    }
  }

  // 获取表格数据
  const getTableData = async () => {
    loading.value = true
    try {
      const res = await BusinessMenuService.getAll(searchForm)
      // 将权限数据中的childs字段转换为children字段，以便el-table能正确展示子级菜单
      const convertedData = convertChildsToChildren(res.data.list || [])
      tableData.value = convertedData
      total.value = res.data.total || 0

      // 构建菜单树数据（排除当前编辑的菜单及其子菜单）
      if (!isEdit.value) {
        menuTreeData.value = buildMenuTree(convertedData)
      }
    } catch (error) {
      console.error('获取菜单数据失败:', error)
      ElMessage.error('获取菜单数据失败')
    } finally {
      loading.value = false
    }
  }

  // 将数据中的 childs 属性转换为 children 属性
  const convertChildsToChildren = (data: BusinessPermissionTreeType[]): BusinessPermissionTreeType[] => {
    return data.map(item => {
      const newItem = { ...item }
      // 如果存在 childs 属性，将其转换为 children 属性
      if (newItem.childs) {
        newItem.children = convertChildsToChildren(newItem.childs)
        delete newItem.childs
      }
      return newItem
    })
  }

  // 构建菜单树
  const buildMenuTree = (data: BusinessPermissionTreeType[]) => {
    const treeData = JSON.parse(JSON.stringify(data))
    return treeData.filter((item: BusinessPermissionTreeType) => {
      return item.resourceType === 'catalog';
    })
  }

  // 搜索
  const handleSearch = () => {
    searchForm.page = 1
    getTableData()
  }

  // 重置
  const handleReset = () => {
    searchForm.permissionName = ''
    searchForm.page = 1
    getTableData()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    searchForm.pageSize = val
    getTableData()
  }

  const handleCurrentChange = (val: number) => {
    searchForm.page = val
    getTableData()
  }

  // 新增菜单
  const handleAdd = async () => {
    isEdit.value = false
    Object.assign(menuForm, {
      permissionId: undefined,
      permissionPid: undefined,
      permissionName: '',
      permissionUri: '',
      permission: '',
      icon: '',
      describe: '',
      resourceType: 'menu',
      sort: 0
    })

    await getMaxSort()
    await getTableData() // 重新获取菜单树数据
    dialogVisible.value = true
  }

  // 新增下级菜单
  const handleAddChild = async (row: BusinessPermissionType) => {
    isEdit.value = false
    Object.assign(menuForm, {
      permissionId: undefined,
      permissionPid: row.permissionId,
      permissionName: '',
      permissionUri: '',
      permission: '',
      icon: '',
      describe: '',
      resourceType: 'menu',
      sort: 0
    })

    await getMaxSort()
    dialogVisible.value = true
  }

  // 编辑菜单
  const handleEdit = async (row: BusinessPermissionType) => {
    isEdit.value = true
    Object.assign(menuForm, row)

    // 获取菜单详情
    try {
      const res = await BusinessMenuService.getById({ permissionId: row.permissionId! })
      Object.assign(menuForm, res.data)
      await getTableData() // 重新获取菜单树数据
      dialogVisible.value = true
    } catch (error) {
      console.error('获取菜单详情失败:', error)
      ElMessage.error('获取菜单详情失败')
    }
  }

  // 删除菜单
  const handleDelete = async (row: BusinessPermissionType) => {
    try {
      await BusinessMenuService.delete({ permissionId: row.permissionId! })
      ElMessage.success('删除成功')
      getTableData()
    } catch (error) {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除菜单失败')
    }
  }

  // 提交菜单
  const submitMenu = async () => {
    if (!menuFormRef.value) return

    await menuFormRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        try {
          if (menuForm.permissionId) {
            // 编辑
            await BusinessMenuService.update(menuForm)
            ElMessage.success('编辑成功')
          } else {
            // 新增
            await BusinessMenuService.save(menuForm)
            ElMessage.success('新增成功')
          }
          dialogVisible.value = false
          getTableData()
        } catch (error) {
          console.error('保存菜单失败:', error)
          ElMessage.error('保存菜单失败')
        } finally {
          submitLoading.value = false
        }
      }
    })
  }

  // 同步菜单
  const handleSyncMenu = () => {
    Object.assign(syncForm, {
      syncAll: true,
      syncBusinessUsername: '',
      delMenu: false
    })
    syncDialogVisible.value = true
  }

  // 提交同步
  const submitSync = async () => {
    if (!syncFormRef.value) return

    await syncFormRef.value.validate(async (valid) => {
      if (valid) {
        syncLoading.value = true
        try {
          await BusinessMenuService.syncMenu(syncForm)
          ElMessage.success('同步成功')
          syncDialogVisible.value = false
        } catch (error) {
          console.error('同步菜单失败:', error)
          ElMessage.error('同步菜单失败')
        } finally {
          syncLoading.value = false
        }
      }
    })
  }

  // 选择图标
  const handleIconChoose = (icon: string) => {
    menuForm.icon = icon
  }

  // 初始化
  onMounted(() => {
    getTableData()
  })
</script>

<style scoped lang="scss">
.table-container {
  overflow-x: auto;
  overflow-y: auto;
  touch-action: pan-y;
}

.pagination-wrapper {
  overflow-x: auto;
  overflow-y: hidden;
  touch-action: pan-x;
  display: flex;
  justify-content: flex-start;
  margin-top: 16px;
  
  :deep(.el-pagination) {
    display: flex;
    justify-content: flex-start;
    min-width: 0;
    margin: 0 !important;
    padding: 0 10px !important;
  }
}

.table-actions {
  display: flex;
  gap: 4px;
}

/* 响应式调整 - 在小屏幕上优化显示 */
@media screen and (max-width: 768px) {
  .table-actions {
    flex-direction: column;
    align-items: center;
    gap: 2px;
  }
}
</style>

<style scoped lang="scss">
  .business-menus-page {
    padding: 20px;

    .search-form {
      padding: 15px;
      margin-bottom: 20px;
      background-color: var(--art-gray-50);
      border-radius: 4px;
    }

    .menus-table {
      margin-bottom: 20px;
    }

    .table-actions {
      display: flex;
      gap: 10px;
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }

    .dialog-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }
  }

  // 响应式设计 - IPad Pro
  @media screen and (max-width: $device-ipad-pro) {
    .business-menus-page {
      padding: 15px;

      .search-form {
        .el-form-item {
          margin-right: 10px;
        }

        .el-input {
          width: 180px !important;
        }
      }
    }
  }

  // 响应式设计 - IPad 竖屏
  @media screen and (max-width: $device-ipad-vertical) {
    .business-menus-page {
      padding: 15px;
    }
  }

  // 响应式设计 - IPad
  @media screen and (max-width: $device-ipad) {
    .business-menus-page {
      padding: 15px;

      .el-dialog {
        width: 80% !important;
        max-width: 500px;
      }
    }
  }

  // 响应式设计 - 手机
  @media screen and (max-width: $device-phone) {
    .business-menus-page {
      padding: 10px;

      .search-form {
        padding: 10px;
        margin-bottom: 15px;

        .el-form-item {
          width: 100%;
          margin-right: 0;
          margin-bottom: 10px;
        }

        .el-input {
          width: 100% !important;
        }

        .el-button {
          margin-bottom: 5px;
        }
      }

      .table-actions {
        gap: 5px;
      }

      .el-table {
        font-size: 12px;
      }

      .el-dialog {
        width: 90% !important;
        max-width: 400px;
        margin: 10vh auto !important;
      }
    }
  }
</style>
